<?php

/*
 * Camelot PHP Tools
 *
 * @version 2.0
 * @author Bendsoft
 * @package PHP Tools
 * @subpackage Camelot
 * @license FreeBSD License (www.bendsoft.com/licensing/)
 * 
 */

/**
 * Class that handles SharePoint Command objects
 * @author Bendsoft
 */
class SharePointQuery extends CamelotExceptionHandling {

    /**
     * The returned camelot xml object 
     * @var CamelotXmlReader
     */
    public $CamelotSoap;

    /**
     * Constructor
     *
     * @param Array|Object $args Classic command array or a SharePointXCommand
     */
    function __construct($args) {

        // Determine what kind of argument that is sent to the constructor
        // If we have an array we must convert this to a command for backwards compatibility
        $type = gettype($args);
        if ($type == "array") {
            if (array_key_exists('sql', $args)) {
                // If the argument array contan SQL lets build a new SharePointSqlCommand
                $command = new SharePointSqlCommand();
                $command->buildCommandFromArray($args);
            } else {
                // Otherwise assume this is a SharePointListCommand
                $command = new SharePointListCommand();
                $command->buildCommandFromArray($args);
            }
        } elseif ($type == "object") {
            // Ie SharePointSqlCommand, SharePointListCommand
            $command = $args;
        } else {
            $this->exception = new CamelotException(null, 408);
            $this->commandStatus = false;
            return;
        }

        // Validate the command using the internal validate method of the class
        $validateResult = $command->isValid();
        if ($validateResult !== true) {
            $this->exception = $validateResult;
            $this->commandStatus = false;
            return;
        }

        // Execute the command
        $commandResult = $command->execute();

        if ($commandResult instanceof CamelotException) {
            $this->exception = $commandResult;
            $this->commandStatus = false;

            // Throw CamelotException
            if (!SILENT_EXCEPTIONS) {
                throw $commandResult;
            }
        } elseif (isset($commandResult->exception) && $commandResult->exception instanceof CamelotException) {
            $this->exception = $commandResult->exception;
            $this->commandStatus = false;
            
            // Throw CamelotException
            if (!SILENT_EXCEPTIONS) {
                throw $commandResult->exception;
            }
            
        } else {
            $this->exception = null;
            $this->commandStatus = true;
            $this->CamelotSoap = $commandResult;
        }

        return;
    }

    /**
     * Destroy stuff when we are done with the class
     */
    function __destruct() {
        unset($this->CamelotSoap);
    }

}

?>
